import _ from 'lodash'
import { getYears } from '@/utils/study.js'
import { region } from '@/utils/modules/settings.js'
import { hkAll, mAll } from '@/data/index.js'

const allValues = region === 'm' ? mAll : hkAll

// 获取年份
const yearValue = _.cloneDeep(getYears(allValues))
// 获取年份选项
const yearOption = _.cloneDeep(getYears(allValues))

const state = {
  // 当前选中的地区
  region,
  // 当前选中年份
  yearValue,
  // 年份选项
  yearOption,
  // 所选年份数据
  allValues: _.cloneDeep(allValues),
  // 所选年份数据备份
  allValuesCopy: _.cloneDeep(allValues),

  // 全局 groupMapBySize
  globalGroupMapBySize: null
}

const mutations = {
  SET_YEAR: (state, year) => {
    const result = Array.isArray(year) ? year : [year]
    state.yearValue = _.cloneDeep(result)
  },

  SET_YEAR_OPTION: (state, option) => {
    const result = Array.isArray(option) ? option : [option]
    state.yearOption = _.cloneDeep(result)
  },

  SET_ALL_VALUES: (state, value) => {
    state.allValues = _.cloneDeep(value)
  },

  SET_ALL_VALUES_COPY: (state, value) => {
    state.allValuesCopy = _.cloneDeep(value)
  },

  SET_REGION: (state, value) => {
    state.region = value
  },

  SET_GLOBAL_GROUP_MAP_BY_SIZE: (state, value) => {
    state.globalGroupMapBySize = _.cloneDeep(value)
  }
}

const actions = {
  setYear({ commit }, year) {
    const arr = Array.isArray(year) && year.length ? year : []
    const result = _.cloneDeep(arr).sort((a, b) => a - b)
    commit('SET_YEAR', result)
  },

  setRegion({ commit }, region) {
    commit('SET_REGION', region)
  },

  // 忽略步进器级别的更新
  setAllValuesForYear({ commit, state }, value) {
    if (!value.length) {
      commit('SET_ALL_VALUES', [])
    } else {
      // 过滤 state.allValuesCopy 中符合年份条件的数据
      const filteredValues = state.allValuesCopy.filter((item) => {
        const year = item.time.split('-')[0] // 提取年份部分
        return value.includes(year) // 判断年份是否在传入的 value 中
      })

      // 提交过滤后的数据
      commit('SET_ALL_VALUES', filteredValues)
    }
  },

  // 忽略步进器级别的更新
  updateRegionLinkedData({ commit }, value) {
    const allValues = value === 'hk' ? _.cloneDeep(hkAll) : _.cloneDeep(mAll)
    const yearValue = getYears(allValues)
    const yearOption = getYears(allValues)

    commit('SET_ALL_VALUES', allValues)
    commit('SET_ALL_VALUES_COPY', allValues)
    commit('SET_YEAR', yearValue)
    commit('SET_YEAR_OPTION', yearOption)
    commit('SET_REGION', value)
  },

  setGlobalGroupMapBySize({ commit }, value) {
    commit('SET_GLOBAL_GROUP_MAP_BY_SIZE', value)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
